package redis

import (
	"context"
	"fmt"
	"strconv"
)

// 添加
func CartCreate(userId, goodsId int64, cart map[string]interface{}) error {
	key := fmt.Sprintf("cart:goods_user_%d:goods_id_%d", userId, goodsId)
	return Client.HMSet(context.Background(), key, cart).Err()
}

// 判断
func CartEx(userId, goodsId int64) bool {
	key := fmt.Sprintf("cart:goods_user_%d:goods_id_%d", userId, goodsId)
	return Client.Exists(context.Background(), key).Val() == 1
}

// 修改
func CartUp(userId, goodsId, num int64) error {
	key := fmt.Sprintf("cart:goods_user_%d:goods_id_%d", userId, goodsId)
	return Client.HIncrBy(context.Background(), key, "num", num).Err()
}

// 删除
func CartDelete(userId, goodsId int64) {
	key := fmt.Sprintf("cart:goods_user_%d:goods_id_%d", userId, goodsId)
	keys := Client.HGetAll(context.Background(), key).Val()
	for _, s := range keys {
		Client.Del(context.Background(), s)
	}
}

// 展示
/*func CartList(userId, goodsId int64) []mysql.Goods {
	key := fmt.Sprintf("cart:goods_user_%d:goods_id_%d", userId, goodsId)
	keys := Client.Keys(context.Background(), key).Val()

	for _, s := range keys {
		CaerMap := Client.HGetAll(context.Background(), s).Val()
		userId, _ := strconv.Atoi(CaerMap["user_id"])
		goodsId, _ := strconv.Atoi(CaerMap["goods_id"])
		goodsTitle := CaerMap["goods_title"]
		goodsNum, _ := strconv.Atoi(CaerMap["goods_num"])
		goodsPrice, _ := strconv.Atoi(CaerMap["goods_price"])
		goodsStatue := CaerMap["goods_statue"]
		var Catrlist mysql.Goods
		list := mysql.Goods{

			UserId:      int64(userId),
			GoodsTitle:  goodsTitle,
			GoodsNum:    goodsNum,
			GoodsPrice:  float64(goodsPrice),
			GoodsStatue: goodsStatue,
		}
		list = append(Catrlist, list)

	}
}*/

func CartChecked(userId int64) error {
	key := fmt.Sprintf("cart:goods_user_id:%d:*", userId)
	kers := Client.HGetAll(context.Background(), key).Val()
	for _, s2 := range kers {
		CaerMap := Client.HGetAll(context.Background(), s2).Val()
		userId, _ := strconv.Atoi(CaerMap["user_id"])
		goodsId, _ := strconv.Atoi(CaerMap["goods_id"])
		num, _ := strconv.Atoi(CaerMap["num"])

		userId = userId
		goodsId = goodsId
		num = num
	}
	return Client.HGetAll(context.Background(), key).Err()
}

func CartSum(userId int64) (err error) {
	key := fmt.Sprintf("cart:goods_user_id:%d:*", userId)
	kers := Client.HGetAll(context.Background(), key).Val()
	for _, s2 := range kers {
		CaerMap := Client.HGetAll(context.Background(), s2).Val()
		price, _ := strconv.ParseFloat(CaerMap["price"], 64)
		num, _ := strconv.Atoi(CaerMap["num"])

		userId = userId
		num += num
		price += price * float64(num)
	}
	return Client.HGetAll(context.Background(), key).Err()
}

func CartEmpty(userId int64) error {
	key := fmt.Sprintf("cart:goods_user_id_%d:*", userId)
	keys := Client.Keys(context.Background(), key).Val()
	for _, s2 := range keys {
		Client.HGetAll(context.Background(), s2)
	}
	return Client.Del(context.Background(), key).Err()
}
